import { useMutation } from '@tanstack/react-query';
import { Form, Input, message, Modal } from 'antd';
import React from 'react';

import api from '@/apis/api';
import localINFO from '@/utils/localInfo';
import { UsbLoginUser } from '@/utils/usbKey/login';

import { Logger } from '../useLogger';

interface ChangePinCodeModalProps {
  visible: boolean;
  setVisible: (visible: boolean) => void;
  userId: number;
  userName: string;
}

const ChangePinCodeModal: React.FC<ChangePinCodeModalProps> = ({
  visible,
  setVisible,
  userId,
  userName,
}) => {
  const [form] = Form.useForm();
  const currentUser = localINFO.getCurrentUserName();

  // 获取后端登录需要的随机数
  const GetRandom = useMutation({
    mutationFn: (params: any) => api.GenRandom(params),
    onSuccess: (data: any) => {
      if (!data?.success) {
        message.open({
          type: 'error',
          key: 'login',
          content: `获取随机数失败, ${data?.message}`,
        });
      }
    },
    onError: () => {
      message.open({
        type: 'error',
        key: 'login',
        content: '获取随机数失败',
      });
    },
  });

  const ChangeUserPinCode = useMutation({
    mutationFn: (params: any) => api.ChangeUserPin(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('修改成功');
      } else {
        message.error(`修改失败, ${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('修改失败');
    },
  });

  // 修改用户密码弹窗
  const handleChangeOk = async () => {
    await form.validateFields();
    // 在这里处理表单提交逻辑
    const data: FieldType = form.getFieldsValue();
    const res = await GetRandom.mutateAsync({
      name: userName,
    });
    const random = res?.data?.random_number;
    let originData;
    let signature;
    if (random) {
      const usbLoginRes: {
        digest: string;
        signature: string;
        originData: string;
      } = await UsbLoginUser(random);
      originData = usbLoginRes?.originData;
      signature = usbLoginRes?.signature;
    }
    ChangeUserPinCode.mutate({
      user_id: userId,
      old_password: data.oldPassword ?? '',
      new_password: data.newPassword,
      originData: originData,
      signature: signature,
    });
    form.resetFields();
    setVisible(false);
  };
  const handleChangeCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  type FieldType = {
    oldPassword?: string;
    newPassword?: string;
    repeatPassword?: string;
  };

  return (
    <>
      <Modal
        title="修改用户密码"
        open={visible}
        onOk={handleChangeOk}
        onCancel={handleChangeCancel}
        cancelText="取消"
        okText="确定"
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form
          form={form}
          preserve={false}
          name="basic"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600, marginTop: 24 }}
          autoComplete="off"
        >
          {userName !== currentUser && (
            <p style={{ marginLeft: 24, color: 'red' }}>
              修改其他用户密码需要插入该用户的usebKey！
            </p>
          )}
          {userName === currentUser && (
            <Form.Item<FieldType>
              label="旧密码"
              name="oldPassword"
              rules={[{ required: true, message: '请输入旧密码！' }]}
            >
              <Input.Password autoComplete="old-password" placeholder="请输入旧密码" />
            </Form.Item>
          )}

          <Form.Item<FieldType>
            label="新密码"
            name="newPassword"
            rules={[{ required: true, message: '请输入新密码！' }]}
          >
            <Input.Password autoComplete="new-password" placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item<FieldType>
            label="确认密码"
            name="repeatPassword"
            rules={[
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve(rule);
                  }
                  return Promise.reject('新密码与确认密码不同！');
                },
              }),
              { required: true, message: '请再输入新密码!' },
            ]}
          >
            <Input.Password autoComplete="new-password" placeholder="请再输入新密码" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default ChangePinCodeModal;
